'use strict'
/**
 * 页面大小自动全屏适配
 * @type {null}
 */
let currRenderDom = null
let currentRectification = ''
let currentRectificationLevel = ''
let resizeListener = null
let timer = null
let currScale = 1
let isAutoScaleRunning = false
let isElRectification = false
const autoScale = {
  init (options = {}, isShowInitTip = true, scaleType = null) {
    if (scaleType === 1) {
      this.scale(options, isShowInitTip)
    } else if (scaleType === 2) {
      this._scale_(options)
    } else if (scaleType === 3) {
      this.scale_scroll(options)
    } else {
      const element = document.getElementById('app')
      element.setAttribute('style', 'height: 100px;')
      element.removeAttribute('style')
    }
  },
  /**
   * 带滚动条，不缩放
   * @param {boolean}
   * el：渲染的dom，默认是 "#app"，必须使用id选择器
   * dw：设计稿的宽度，默认是 1920
   * dh：设计稿的高度，默认是 929 ，如果项目以全屏展示，则可以设置为1080
   */
  scale_scroll (options = {}) {
    const {
      designWidth = 1920,
      dw = 1920,
      designHeight = 1080,
      dh = 1080,
      renderDom = typeof options === 'string' ? options : '#app',
      el = typeof options === 'string' ? options : '#app'
    } = options
    currRenderDom = el || renderDom
    let dom = document.querySelector(el)
    dom.style.height = `${dh || designHeight}px`
    dom.style.width = `${dw || designWidth}px`
    dom.style.position = `absolute`
    dom.style.left = `0`
    dom.style.top = `0`
    dom.style.bottom = `0`
    dom.style.right = `0`
    dom.style.margin = `0 auto`
  },
  /**
   * 撑满屏幕
   * @param {boolean}
   * el：渲染的dom，默认是 "#app"，必须使用id选择器
   * dw：设计稿的宽度，默认是 1920
   * dh：设计稿的高度，默认是 929 ，如果项目以全屏展示，则可以设置为1080
   * resize：是否监听resize事件，默认是 true
   * ignore：忽略缩放的元素（该元素将反向缩放）
   * transition：过渡时间，默认是 0.6
   * delay：默认是 1000
   */
  scale (options = {}, isShowInitTip = true) {
    if (isShowInitTip) {
      // console.log(`%c` + `autoScale.js` + ` is running`, `font-weight: bold; color: #ffb712; background:linear-gradient(-45deg, #bd34fe 50%, #47caff 50% );background: -webkit-linear-gradient( 120deg, #bd34fe 30%, #41d1ff );background-clip: text;-webkit-background-clip: text; -webkit-text-fill-color:linear-gradient( -45deg, #bd34fe 50%, #47caff 50% ); padding: 8px 12px; border-radius: 4px;`)
    }
    const {
      designWidth = 1920,
      dw = 1920,
      designHeight = 929,
      dh = 929,
      renderDom = typeof options === 'string' ? options : '#app',
      el = typeof options === 'string' ? options : '#app',
      resize = true,
      ignore = [],
      transition = 'none',
      delay = 0
    } = options
    currRenderDom = el || renderDom
    let dom = document.querySelector(el)
    if (!dom) {
      // console.error(`autoScale: '${el}' is not exist`)
      return
    }
    const style = document.createElement('style')
    const ignoreStyle = document.createElement('style')
    style.lang = 'text/css'
    ignoreStyle.lang = 'text/css'
    style.id = 'autoScale-style'
    ignoreStyle.id = 'ignoreStyle'
    style.innerHTML = `
      body {
        overflow: hidden;
      }
    `
    dom.appendChild(style)
    dom.appendChild(ignoreStyle)
    dom.style.height = `${dh || designHeight}px`
    dom.style.width = `${dw || designWidth}px`
    dom.style.transformOrigin = `0 0`
    keepFit(dw || designWidth, dh || designHeight, dom, ignore)
    resizeListener = () => {
      clearTimeout(timer)
      if (delay !== 0) {
        timer = setTimeout(() => {
          keepFit(dw || designWidth, dh || designHeight, dom, ignore)
          isElRectification && elRectification(currentRectification, currentRectificationLevel)
        }, delay)
      } else {
        keepFit(dw || designWidth, dh || designHeight, dom, ignore)
        isElRectification && elRectification(currentRectification, currentRectificationLevel)
      }
    }
    resize && window.addEventListener('resize', resizeListener)
    isAutoScaleRunning = true
    setTimeout(() => {
      dom.style.transition = `${transition}s`
    })
  },
  scale_off (el = '#app') {
    try {
      isElRectification = false
      window.removeEventListener('resize', resizeListener)
      document.querySelector('#autoScale-style').remove()
      document.querySelector(currRenderDom || el).style = ''
      for (let item of document.querySelectorAll(currentRectification)) {
        item.style.width = ``
        item.style.height = ``
        item.style.transform = ``
      }
    } catch (error) {
      // console.error(`autoScale: Failed to remove normally`, error)
      isAutoScaleRunning = false
    }
    isAutoScaleRunning && console.log(`%c` + `AutoScale.js` + ` is off`, `font-weight: bold;color: #707070; background: #c9c9c9; padding: 8px 12px; border-radius: 4px;`)
  },
  /**
   * 撑满屏幕(两边留白)
   * @param {boolean}
   * el：渲染的dom，默认是 "#app"，必须使用id选择器
   * dw：设计稿的宽度，默认是 1920
   * dh：设计稿的高度，默认是 929 ，如果项目以全屏展示，则可以设置为1080
   * resize：是否监听resize事件，默认是 true
   * transition：过渡时间，默认是 0.6
   */
  _scale_ (options = '#app') {
    const {
      designWidth = 1920,
      dw = 1920,
      designHeight = 1080,
      dh = 1080,
      renderDom = typeof options === 'string' ? options : '#app',
      el = typeof options === 'string' ? options : '#app',
      resize = Math.min(window.innerWidth / dw || designWidth, window.innerHeight / dh || designHeight),
      transition = 'all'
    } = options
    currRenderDom = el || renderDom
    let dom = document.querySelector(el)
    dom.style.height = `${dh || designHeight}px`
    dom.style.width = `${dw || designWidth}px`
    dom.style.transformOrigin = `0 0`
    dom.style.position = `absolute`
    dom.style.left = `50%`
    dom.style.top = `50%`
    dom.style.transition = `${transition}s`
    dom.style.transform = `scale(${resize}) translate(-50%,-50%)`
    resizeListener = () => {
      const scale = Math.min(window.innerWidth / dw || designWidth, window.innerHeight / dh || designHeight)
      dom.style.transition = `${transition}s`
      dom.style.transform = `scale(${scale}) translate(-50%,-50%)`
    }
    window.addEventListener('resize', resizeListener)
  }
}
function elRectification (el, level = 1) {
  if (!isAutoScaleRunning) {
    // console.error('autoScale.js：autoScale has not been initialized yet')
  }
  !el && console.error(`AutoScale.js：bad selector: ${el}`)
  currentRectification = el
  currentRectificationLevel = level
  const currEl = document.querySelectorAll(el)
  if (currEl.length === 0) {
    // console.error('autoScale.js：elRectification found no element')
    return
  }
  for (let item of currEl) {
    if (!isElRectification) {
      item.originalWidth = item.clientWidth
      item.originalHeight = item.clientHeight
    }
    let rectification = currScale === 1 ? 1 : currScale * level
    item.style.width = `${item.originalWidth * rectification}px`
    item.style.height = `${item.originalHeight * rectification}px`
    item.style.transform = `scale(${1 / currScale})`
    item.style.transformOrigin = `0 0`
  }
  isElRectification = true
}
function keepFit (dw, dh, dom, ignore) {
  let clientHeight = document.documentElement.clientHeight
  let clientWidth = document.documentElement.clientWidth
  currScale = (clientWidth / clientHeight < dw / dh) ? (clientWidth / dw) : (clientHeight / dh)
  dom.style.height = `${clientHeight / currScale}px`
  dom.style.width = `${clientWidth / currScale}px`
  dom.style.transform = `scale(${currScale})`
  for (let item of ignore) {
    let itemEl = item.el || item.dom
    if (!itemEl) {
      // console.error(`autoScale: bad selector?: ${itemEl}`)
      continue
    }
    let realScale = (item.scale ? item.scale : 1 / currScale)
    let realFontSize = realScale !== currScale ? item.fontSize : 'autoScale'
    let realWidth = realScale !== currScale ? item.width : 'autoScale'
    let realHeight = realScale !== currScale ? item.height : 'autoScale'
    let regex = new RegExp(`${itemEl}(\x20|{)`, 'gm')
    let isIgnored = regex.test(document.querySelector('#ignoreStyle').innerHTML)
    if (isIgnored) {
      continue
    }
    document.querySelector('#ignoreStyle').innerHTML += `\n${itemEl} {
      transform: scale(${realScale})!important;
      transform-origin: 0 0;
      width: ${realWidth}px!important;
      height: ${realHeight}px!important;
    }`
    document.querySelector('#ignoreStyle').innerHTML += `\n${itemEl} div ,${itemEl} span,${itemEl} a,${itemEl} * {
    font-size: ${realFontSize}px;
    }`
  }
}

export {
  elRectification
}
export default autoScale
